package com.example.coursehub.controller;

import com.example.coursehub.service.CourseService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.coursehub.entity.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/courses")
public class CourseController {

    @Autowired
    private CourseService courseService;
    @Autowired
    private ObjectMapper objectMapper;

    // 课程基础操作
    /**
     * 创建一个新的课程
     * @param course 要创建的课程对象
     * @return 创建成功后的课程对象及HTTP状态码201（CREATED）
     */
    @PostMapping("/createCourse")
    public ResponseEntity<Course> createCourse(@RequestBody Map<String,Object> payload) {
        // 从 payload 中提取 course 对象
        Course course = objectMapper.convertValue(payload.get("courses"), Course.class);

        // 提取 userId
        String userId = (String) payload.get("userId");
        System.out.println("userId: " + userId);

        // 调用 service 创建课程并绑定教师
        Course createdCourse = courseService.createCourse(course, userId);

        return new ResponseEntity<>(createdCourse, HttpStatus.CREATED);
    }

    /**
     * 更新一个课程的信息
     * @param courseId 要更新的课程的ID
     * @param course 更新后的课程对象
     * @return 更新后的课程对象及HTTP状态码200（OK）
     */
    @PutMapping("/{courseId}")
    public ResponseEntity<Course> updateCourse(@PathVariable String courseId, @RequestBody Course course) {
        return ResponseEntity.ok(courseService.updateCourse(courseId, course));
    }

    /**
     * 根据课程ID删除一个课程
     * @param courseId 要删除的课程的ID
     * @return HTTP状态码204（NO_CONTENT）
     */
    @DeleteMapping("/{courseId}")
    public ResponseEntity<Void> deleteCourse(@PathVariable String courseId) {
        courseService.deleteCourse(courseId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 根据课程ID获取一个课程
     * @param courseId 要获取的课程的ID
     * @return 获取到的课程对象及HTTP状态码200（OK）
     */
    @GetMapping("/{courseId}")
    public ResponseEntity<Course> getCourseById(@PathVariable String courseId) {
        return ResponseEntity.ok(courseService.getCourseById(courseId));
    }

    /**
     * 获取所有课程
     * @return 所有课程的列表及HTTP状态码200（OK）
     */
    @GetMapping
    public ResponseEntity<List<Course>> getAllCourses() {
        return ResponseEntity.ok(courseService.getAllCourses());
    }

    @GetMapping("/users/{userId}/roles/{role}/courses")
    public ResponseEntity<List<Course>> getCoursesByUserAndRole(@PathVariable String userId, @PathVariable String role) {
        System.out.println("到达controller层，接收到 userId: " + userId + ", role: " + role);
        return ResponseEntity.ok(courseService.getCoursesByUserIdAndRole(userId, role));
    }

    /**
     * 学生加入课程并初始化收藏题库和错题库
     */
    @PostMapping("/enroll")
    public ResponseEntity<Void> enrollStudent(@RequestBody Map<String, String> payload) {
        String courseId = payload.get("courseId");
        String userId = payload.get("userId");

        if (courseId == null || userId == null) {
            return ResponseEntity.badRequest().build();
        }

        courseService.enrollStudentInCourse(courseId, userId);

        return ResponseEntity.ok().build();
    }

    /**
     * 根据课程ID获取该课程下所有的班级
     * @param courseId 课程ID
     * @return 该课程下所有班级的列表及HTTP状态码200（OK）
     */
    @GetMapping("/{courseId}/classes")
    public ResponseEntity<List<Classes>> getClassesForCourse(@PathVariable String courseId) {
        List<Classes> classes = courseService.getClassesByCourseId(courseId);
        if (classes.isEmpty()) {
            return ResponseEntity.ok(classes);
        }
        return ResponseEntity.ok(classes);
    }

    /**
     * 获取指定课程的所有教师
     * @param courseId 课程ID
     * @return 该课程的所有教师列表及HTTP状态码200（OK）
     */
    @GetMapping("/{courseId}/teachers")
    public ResponseEntity<List<User>> getTeachersInCourse(@PathVariable String courseId) {
        List<User> teachers = courseService.getTeachersInCourse(courseId);
        // ObjectMapper mapper = new ObjectMapper(); // 仅当此处需要明确序列化为JSON字符串时才需要
        // String jsonOutput = mapper.writeValueAsString(teachers); // 如果只返回ResponseEntity.ok(teachers)，则不需要此行
        return ResponseEntity.ok(teachers);
    }

    /**
     * 将一个教师添加到指定课程
     * @param courseId 课程ID
     * @param userId 教师ID
     * @return HTTP状态码200（OK）
     */
    @PostMapping("/{courseId}/teachers/{userId}")
    public ResponseEntity<Void> addTeacherToCourse(@PathVariable String courseId, @PathVariable String userId) {
        courseService.addTeacherToCourse(courseId, userId);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 将一个教师从指定课程移除
     * @param courseId 课程ID
     * @param userId 教师ID
     * @return HTTP状态码200（OK）
     */
    @DeleteMapping("/{courseId}/teachers/{userId}")
    public ResponseEntity<Void> removeTeacherFromCourse(@PathVariable String courseId, @PathVariable String userId) {
        courseService.removeTeacherFromCourse(courseId, userId);
        return new ResponseEntity<>(HttpStatus.OK);
    }
    /**
     * 为指定课程添加一个章节
     * @param courseId 课程ID
     * @param chapter 要添加的章节对象
     * @return HTTP状态码201（CREATED）
     */
    @PostMapping("/{courseId}/chapters")
    public ResponseEntity<Void> addChapter(@PathVariable String courseId, @RequestBody Chapter chapter) {
        courseService.addChapter(courseId, chapter);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    /**
     * 根据课程ID和章节ID删除一个章节
     * @param courseId 课程ID
     * @param chapterId 章节ID
     * @return HTTP状态码204（NO_CONTENT）
     */
    @DeleteMapping("/{courseId}/chapters/{chapterId}")
    public ResponseEntity<Void> deleteChapter(@PathVariable String courseId, @PathVariable String chapterId) {
        courseService.deleteChapter(courseId, chapterId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 根据课程ID获取该课程的所有章节
     * @param courseId 课程ID
     * @return 该课程的所有章节列表及HTTP状态码200（OK）
     */
    @GetMapping("/{courseId}/chapters")
    public ResponseEntity<List<Chapter>> getChapters(@PathVariable String courseId) {
        return ResponseEntity.ok(courseService.getChapters(courseId));
    }

    // 课程资料管理
    /**
     * 为指定课程的指定章节添加一个资料
     * @param courseId 课程ID
     * @param chapterId 章节ID
     * @param material 要添加的资料对象
     * @return HTTP状态码201（CREATED）
     */
    @PostMapping("/{courseId}/chapters/{chapterId}/materials")
    public ResponseEntity<Void> addMaterial(
            @PathVariable String courseId,
            @PathVariable String chapterId,
            @RequestBody Material material) {
        courseService.addMaterial(courseId, chapterId, material);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    /**
     * 根据课程ID、章节ID和资料ID删除一个资料
     * @param courseId 课程ID
     * @param chapterId 章节ID
     * @param materialId 资料ID
     * @return HTTP状态码204（NO_CONTENT）
     */
    @DeleteMapping("/{courseId}/chapters/{chapterId}/materials/{materialId}")
    public ResponseEntity<Void> deleteMaterial(
            @PathVariable String courseId,
            @PathVariable String chapterId,
            @PathVariable String materialId) {
        courseService.deleteMaterial(courseId, chapterId, materialId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @GetMapping("/course/{courseId}/teachers")
    public ResponseEntity<List<String>> getTeachersByCourseId(@PathVariable String courseId) {
        List<String> teachers = courseService.getTeachersByCourseId(courseId);
        return ResponseEntity.ok(teachers);
    }

//    @GetMapping("/{courseId}/{chapterId}")
//    public ResponseEntity<Chapter> getChapter(
//            @PathVariable String courseId,
//            @PathVariable String chapterId) {
//        Chapter chapter = courseService.getChapterById(courseId, chapterId);
//        return ResponseEntity.ok(chapter);
//    }

}